﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using System.Text.Json.Serialization;
using MessagePack;

namespace SerializableDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            MessagePack();
            Xml();
            TextJson();
            Json();

            Console.ReadKey();
        }

        static void MessagePack()
        {
            var books = new List<Book>();
            for (int i = 0; i < 1_000_000; i++)
            {
                string id = i.ToString();
                books.Add(new Book { Name = id, Id = id });
            }

            var bytes = MessagePackSerializer.Serialize(books);
            var sw = Stopwatch.StartNew();
            _ = MessagePackSerializer.Deserialize<List<Book>>(bytes);
            sw.Stop();

            Console.WriteLine($"MessagePack {sw.Elapsed}");
        }

        static void Xml()
        {
            var books = new List<Book>();
            for (int i = 0; i < 1_000_000; i++)
            {
                string id = i.ToString();
                books.Add(new Book { Name = id, Id = id });
            }

            var serializer = new XmlSerializer(typeof(List<Book>));
            var mem = new MemoryStream();
            serializer.Serialize(mem, books);
            mem.Position = 0;

            var sw = Stopwatch.StartNew();
            _ = serializer.Deserialize(mem) as List<Book>;
            sw.Stop();

            Console.WriteLine($"Xml {sw.Elapsed}");
        }

        static void Json()
        {
            var books = new List<Book>();
            for (int i = 0; i < 1_000_000; i++)
            {
                string id = i.ToString();
                books.Add(new Book { Name = id, Id = id });
            }

            var serializer = JsonConvert.SerializeObject(books);

            var sw = Stopwatch.StartNew();
            _ = JsonConvert.DeserializeObject<List<Book>>(serializer);
            sw.Stop();

            Console.WriteLine($"Json {sw.Elapsed}");
        }

        static void TextJson()
        {
            var books = new List<Book>();
            for (int i = 0; i < 1_000_000; i++)
            {
                string id = i.ToString();
                books.Add(new Book { Name = id, Id = id });
            }

            var serializer = System.Text.Json.JsonSerializer.Serialize(books);

            var sw = Stopwatch.StartNew();
            _ = System.Text.Json.JsonSerializer.Deserialize<List<Book>>(serializer);
            sw.Stop();

            Console.WriteLine($"TextJson {sw.Elapsed}");
        }
    }

    [Serializable]
    [MessagePackObject]
    public class Book
    {
        [Key(0)]
        public string Id { get; set; } = null!;
        [Key(1)]
        public string Name { get; set; } = null!;
    }
}
